/**
 * 该文件可自行根据业务逻辑进行调整
 */
import type { HttpResponse } from '@vben/request';

import { useAppConfig } from '@vben/hooks';
import { preferences } from '@vben/preferences';
import { RequestClient } from '@vben/request';
import { useAccessStore } from '@vben/stores';

import { message } from 'ant-design-vue';

import { useAuthStore } from '#/store';

const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
const unAuthorizedHandlerFn = async (loginExpired: boolean = false) => {
  const accessStore = useAccessStore();
  const authStore = useAuthStore();
  accessStore.setAccessToken(null);
  // 退出登录
  if (loginExpired) {
    accessStore.setLoginExpired(loginExpired);
  } else {
    await authStore.logout();
  }
};
function createRequestClient(baseURL: string) {
  const client = new RequestClient({
    baseURL,
    // 为每个请求携带 Authorization
    makeAuthorization: () => {
      return {
        // 默认
        key: 'Signature',
        tokenHandler: () => {
          const accessStore = useAccessStore();
          return {
            refreshToken: `${accessStore.refreshToken}`,
            token: `${accessStore.accessToken}`,
          };
        },
        unAuthorizedHandler: unAuthorizedHandlerFn,
      };
    },
    makeErrorMessage: (msg) => message.error(msg),

    makeRequestHeaders: () => {
      return {
        // 为每个请求携带 Accept-Language
        'Accept-Language': preferences.app.locale,
      };
    },
  });
  client.addResponseInterceptor<HttpResponse>((response) => {
    const { data: responseData } = response;
    const { code, datas, msg } = responseData;
    if (code === 9999 || code === 9998) {
      unAuthorizedHandlerFn(code === 9998);
      return;
    }
    code !== 0 && message.error(msg);
    let result = code === 0 ? datas : null;
    if (result) {
      // 增加返回code
      result.retCode = code;
    } else {
      result = { retCode: code };
    }
    return result;
  });
  return client;
}

export const requestClient = createRequestClient(apiURL);
